package br.com.skytef.utils;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLConnection;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.sun.org.apache.xml.internal.serializer.utils.Utils;

public class NavsDownload {
	private ServletContext context;
	private HttpServletResponse response;

	public NavsDownload(HttpServletResponse response, ServletContext context) {
		this.context = context;
		this.response = response;
	}

	public void downloadFileLocal(String path) {
		try {			
			String filename = context.getRealPath(path);

			File f = new File(filename);
			int length = 0;
			ServletOutputStream op = response.getOutputStream();
			String mimetype = context.getMimeType(path);

			int size = (int) f.length();
			response.setContentType((mimetype != null) ? mimetype: "application/octet-stream");
			response.setContentLength(size);

			byte[] buffer = new byte[4096];
			DataInputStream in = new DataInputStream(new FileInputStream(f));

			String dado = "";
			while ((in != null) && ((length = in.read(buffer)) != -1)) {
				op.write(buffer, 0, length);
				//dado = dado + new String(buffer).substring(0, length);
			}

			in.close();
			op.flush();
			op.close();

		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}

	public HttpServletResponse downloadFtpRemoto() {
		return response;
	}
	
	public void downloadFileRemoto(String filePath) throws IOException {
				
		DownloadFtp ftp = new DownloadFtp();
		InputStream inputStream = ftp.getInputStream(filePath);
		URLConnection conn = ftp.getConn();
		conn.setConnectTimeout(3600);
		
		int length = 0;
		ServletOutputStream op = response.getOutputStream();
		String mimetype = null;
		
		int contentLength = inputStream.available();
				
		response.setContentType((mimetype != null) ? mimetype: "application/octet-stream");
		response.setContentLength(4000000);//3051195
		
		byte[] buffer = new byte[4096];
		DataInputStream in = new DataInputStream(inputStream);

		long tamanho = 0;
		try {
			while ((in != null) && ((length = in.read(buffer)) != -1)) {
				op.write(buffer, 0, length);
			}			
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}

		conn = null;
		inputStream.close();
		in.close();
		op.flush();
		op.close();		
	}
}
